﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Barbar.UrlGuard.Dal;
using Barbar.UrlGuard.BL;
using System.Globalization;
using System.Threading;
using Barbar.UrlGuard.Dal.Persist;

namespace Barbar.UrlGuard.Controls {
  public partial class ConfigurationCommon : UserControl, IInjector<DataContext> {
    public ConfigurationCommon() {
      InitializeComponent();
    }

    protected override void OnLoad(EventArgs e) {
      base.OnLoad(e);

      if (!this.DesignMode) {
        ITranslator translator = ServiceLocator.Instance.Resolve<ITranslator>();
        foreach (var cultureInfo in translator.GetLanguagesAvailable()) {
          cbxLanguage.Items.Add(cultureInfo);
        }
      }
    }

    #region IInjector<DataContext> Members

    public void SaveData(DataContext instance) {
      instance.SecondsToTimeout = (int)txtSeconds.Value;

      IAutoStartupService startupService = ServiceLocator.Instance.Resolve<IAutoStartupService>();
      startupService.SetAutoRun(chxRunAtStartup.Checked);

      instance.LanguageID = ((CultureInfo)cbxLanguage.SelectedItem).LCID;
    }

    #endregion

    #region IReadOnlyInjector<DataContext> Members

    public void LoadData(DataContext readOnlyInstance) {
      if (readOnlyInstance == null) {
        txtSeconds.Value = 30m;
      }

      txtSeconds.Value = readOnlyInstance.SecondsToTimeout;

      int index = 0;
      foreach (CultureInfo cultureInfo in cbxLanguage.Items) {
        if (Thread.CurrentThread.CurrentCulture.LCID == cultureInfo.LCID) {
          cbxLanguage.SelectedIndex = index;
          break;
        }
        index++;
      }

      IAutoStartupService startupService = ServiceLocator.Instance.Resolve<IAutoStartupService>();
      chxRunAtStartup.Checked = startupService.IsAutoRunSet();
    }

    #endregion

    private void clearHistoryButton_Click(object sender, EventArgs e)
    {
        // Clear the log history
        ServiceLocator.Instance.Resolve<IHistoryPersistor>().ClearHistory();
    }
  }
}
